/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.ieslaferreria.creditsintesis.rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;

/**
 * crea el servidor
 * @author Administrador
 */

public class ServerImpl extends java.rmi.server.UnicastRemoteObject implements Server{


    protected ArrayList<Partida> partides = new ArrayList<Partida>();
    
      public ServerImpl() throws RemoteException, MalformedURLException{
          super();
      }

      public ServerImpl(int port) throws RemoteException {
        super(port);
    }


    public static void registerToRegistry(String name, Remote obj, boolean create) throws RemoteException, MalformedURLException{

        if (name == null) throw new IllegalArgumentException("registration name can not be null");

        try {
            Naming.rebind(name, obj);
        } catch (RemoteException ex){
            if (create) {
                Registry r = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
                r.rebind(name, obj);
            } else throw ex;
        }
    }

    public Pont addClient(int id, Pont pont, String alias, boolean flag) throws RemoteException {
        Partida part;

        part = this.partides.get(id);
        part.addClient(pont, alias,flag);
        return new PontImpl(part.getListener(),"partida" + id);

    }
        

    public int countPartides() throws RemoteException {
        return this.partides.size();
    }

    public int countClients(int com) throws RemoteException {
        if(this.partides.size()==0){
            return 0;
        }
        return ((Partida)this.partides.get(com)).countClients();
    }

    public void removeClient(int idCom, String alias, Pont pont) throws RemoteException {
         ((Partida) this.partides.get(idCom)).removeClients(alias, pont);
         if(((Partida) this.partides.get(idCom)).countClients()==0){
             this.partides.remove(idCom);
         }
    }
    /*Por ahora solo existe la partida 0*/
    public Partida getPartida(int numPartida){
        return this.partides.get(numPartida);

    }

}


